import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import dynamicRouter from './routerList.js'

Vue.use(VueRouter)

const routes = [
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "login" */ "@/views/login/index"),
  },
  {
    path: "/404",
    name: "404",
    component: () =>
      import(/* webpackChunkName: "error-page" */ "@/views/error-page/404"),
  },
  {
    path: "/index",
    name: "views",
    component: () =>
      import(/* webpackChunkName: "views" */ "@/views/index.vue"),
    children: [
      ...dynamicRouter
    ]
  }
];

// 防止连续点击多次路由报错
// 解决push
// let routerPush = VueRouter.prototype.push;
// VueRouter.prototype.push = function push(location) {
//   return routerPush.call(this, location).catch(err => err)
// }
// // 解决replace
// let originalReplace = VueRouter.prototype.replace
// VueRouter.prototype.replace= function replace(location) {
//   return originalReplace.call(this, location).catch(err => err)
// }

const router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach(async (to, from, next) => {
  // next()里面带参数，会无限循环beforeEach的过程
  if (to.path === "/login") {
    next();
    return;
  }

  // 页面刷新时menu会被清空，若依系统类似，刷新会重新请求菜单，创建动态路由。
  let menu = store.state.permission.menu
  if (menu.length === 0) {
    // 重新生成路由与菜单
    const res = await store.dispatch("permission/generateRoutes")
    if (!res || res.length === 0) {
      // 此处带参数也会再走一次beforeEach
      next({ path: "/login" });
    } else {
      //1、menu为空，store里重新生成菜单，res有值，走到此处，触发循环。
      next({ ...to, replace: true })
    }
    return
  }
  // 找不到对应菜单时
  let menuUrl = store.state.permission.menuUrl
  if (to.matched.length === 0 || !menuUrl.includes(to.path)) {
    let path = to.path === "/" ? "/home" : "/404"
    // replace:true 导航不会留下history记录，点击浏览器回退按钮不会再回到这个路由。
    next({ path, replace: true })
    return
  }
  //2、第二次beforeEach时，menu有值了，跳到次处退出循环。
  next();
})
export default router
